﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using LSEntity;
using MySql.Data.MySqlClient;

namespace LSData
{
    public class QuestionData : DataBase
    {
        #region QuestionTypeField

        private const string QuestionTypeField = @"{0}ID,
                                        {0}Question_Type_ID as TypeId,
                                        {0}Curriculum_id as CurriculumId,
                                        {0}Category as Category,
                                        {0}EasyHard as EasyHard,
                                        {0}Description as Description";

        #endregion

        #region QuestionField
        private const string QuestionField = @"{0}Question_ID as QuestionId,
                                                {0}Source_ID as SourceId,
                                                {0}Question_Type_ID as QuestionTypeId,
                                                {0}Knowledge_Id as KnowledgeId,
                                                {0}Group_num as GroupNum,
                                                {0}Curriculum_ID as CurriculumId,
                                                {0}Grade_ID as GradeId,
                                                {0}Module as ModuleId,
                                                {0}Unit as UnitId,
                                                {0}Assignment as AssignmentId,
                                                {0}Question_Num as QuestionNum,
                                                {0}Image as Image,
                                                {0}Sound as Sound,
                                                {0}Question as QuestionTitle,
                                                {0}Answer as Answer,
                                                {0}Distracter1 as Distracter1,
                                                {0}Distracter2 as Distracter2,
                                                {0}Distracter3 as Distracter3,
                                                {0}Translation as Translation,
                                                {0}Audio_Text as AudioText,
                                                {0}isNew as IsNew,
                                                {0}Last_Updated_By as LastUpdatedBy,
                                                {0}Last_Update_Time as LastUpdateTime,
                                                {0}Count_Researcher as CountResearcher,
                                                {0}Count_Popular as CountPopular,
                                                {0}Difficulty as Difficulty";

        #endregion

        public static List<QuestionType> QuestionTypeForOTGetList(int examId)
        {
            var cacheName = String.Format("QuestionTypeForOTGetList{0}", examId);
            const int paperId = 1;
            const string examIdParame = "ExamId";
            const string paperIdParame = "PaperId";
            var sql = String.Format(@"select distinct {2} 
                                        from sseat_ot_question a 
                                        join question b on a.questionid = b.question_id
                                        join question_type c on b.question_type_id = c.Question_Type_ID 
                                        where a.sub_question_flag=0 and a.examid=@{0} and a.paperid=@{1} order by a.id",
                                    examIdParame, paperIdParame, String.Format(QuestionTypeField, "c."));
            return GetList<QuestionType>(sql, EConn, cacheName, 30, new List<MySqlParameter>
                                                                        {
                                                                            MakeParameter(examIdParame,
                                                                                          MySqlDbType.Int32, examId),
                                                                            MakeParameter(paperIdParame,
                                                                                          MySqlDbType.Int32,
                                                                                          paperId)
                                                                        }).ToList();
        }

        public static List<QuestionForOT> QuestionForOTGetList(int examId)
        {
            var cacheName = String.Format("QuestionForOTGetList{0}", examId);
            const int paperId = 1;
            const string examIdParame = "ExamId";
            const string paperIdParame = "PaperId";
            var sql = String.Format(@"select 
                                        ExamId as ExamId,
                                        PaperId as PaperId,
                                        QuestionId as QuestionId,
                                        Score as Score,
                                        Sub_Question_Flag as SubQuestionFlag
                                        from sseat_ot_question 
                                        where examid=@{0} and paperid=@{1} order by id", examIdParame, paperIdParame);
            var result = GetList<QuestionForOT>(sql, EConn, cacheName, 30, new List<MySqlParameter>
                                                                               {
                                                                                   MakeParameter(examIdParame,
                                                                                                 MySqlDbType.Int32,
                                                                                                 examId),
                                                                                   MakeParameter(paperIdParame,
                                                                                                 MySqlDbType.Int32,
                                                                                                 paperId)
                                                                               }).ToList();
            result.ForEach(m => m.Question = QuestionGet(m.QuestionId));
            return result;
        }

        public static Question QuestionGet(int questionId)
        {
            var sql = String.Format("select {0} from question where Question_ID={1}",
                                    String.Format(QuestionField, String.Empty), questionId);
            return GetInfo<Question>(sql, EConn);
        }

        private static readonly object SyncRoot = new object();

        /// <summary>
        /// 通过question_type_id,curriculum_id, OnlineOrPrint 获取Description
        /// </summary>
        /// <param name="questionTypeId"></param>
        /// <param name="curriculumId"></param>
        /// <param name="onlineOrPrint"></param>
        /// <returns></returns>
        public static string QuestionTypeGetDescription(int questionTypeId, int curriculumId, int onlineOrPrint = 0)
        { 
            const string cacheKey = "AllQuestionType";
            var typeDescription = HttpRuntime.Cache[cacheKey] as DataTable;
            if (typeDescription == null || typeDescription.Rows.Count <= 0)
            {
                lock (SyncRoot)
                {
                    typeDescription = HttpContext.Current.Cache[cacheKey] as DataTable;
                    if (typeDescription == null || typeDescription.Rows.Count <= 0)
                    {
                        #region
                        using (var mp = new MySqlProvider(EConn))
                        {
                            const string strsql = @"select * from question_type_description";
                            typeDescription = mp.ExecuteTable(strsql);
                        }
                        #endregion
                        HttpRuntime.Cache.Add(cacheKey, typeDescription, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(30), CacheItemPriority.High, null);
                    }
                }
            }

            var dr = typeDescription.Select("question_type_id=" + questionTypeId + " and (curriculum_id=0 or curriculum_id=" + curriculumId + "  )", "curriculum_id desc");
            if (dr.Length != 0)
            {
                var dt1 = typeDescription.Clone();
                foreach (var row in dr)
                {
                    dt1.ImportRow(row);
                }
                var dr1 = dt1.Select("curriculum_id=" + curriculumId + " and( ForOnline=0 or ForOnline=" + onlineOrPrint + " )", "ForOnline desc");
                if (dr1.Length != 0)
                {
                    return dr1[0]["description"].ToString();
                }
                dr1 = dt1.Select("curriculum_id=0 and( ForOnline=0 or ForOnline=" + onlineOrPrint + " )", "ForOnline desc");
                return dr1.Length != 0 ? dr1[0]["description"].ToString() : "无";
            }
            return "无";
        }
    }
}
